﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.UI;
using System.Text;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:GoogleMap runat=server></{0}:GoogleMap>")]
    public class GoogleMap : Panel
    {

        public string ApiKey { get { return Settings.SettingsManager.GoogleAPIKey; } }
        public GoogleMapType MapType
        {
            get
            {
                object obj = ViewState["GoogleMapType"]; if (obj == null) { return GoogleMapType.Roadmap; }
                return (GoogleMapType)obj;
            }
            set { ViewState["GoogleMapType"] = value; }
        }

        public decimal Latitude
        {
            get { object obj = ViewState["Latitude"]; return (obj == null) ? 0 : Convert.ToDecimal(obj); }
            set { ViewState["Latitude"] = value; }
        }

        public decimal Longitude
        {
            get { object obj = ViewState["Longitude"]; return (obj == null) ? 0 : Convert.ToDecimal(obj); }
            set { ViewState["Longitude"] = value; }
        }

        public string CentrePoint
        {
            get { object obj = ViewState["CentrePoint"]; return (obj == null ? "" : obj.ToString()); }
            set { ViewState["CentrePoint"] = value; }
        }

        public bool ShowMarkerAtCentrePoint
        {
            get { object obj = ViewState["ShowMarkerAtCentrePoint"]; return (obj == null ? true : Convert.ToBoolean(obj)); }
            set { ViewState["ShowMarkerAtCentrePoint"] = value; }
        }

        public string CentrePointCountry
        {
            get { object obj = ViewState["CentrePointCountry"]; return (obj == null ? "" : obj.ToString()); }
            set { ViewState["CentrePointCountry"] = value; }
        }

        public string MarkerTitle
        {
            get { object obj = ViewState["MarkerTitle"]; return (obj == null ? "" : obj.ToString()); }
            set { ViewState["MarkerTitle"] = value; }
        }

        public Int32 ZoomLevel
        {
            get { object obj = ViewState["ZoomLevel"]; return (obj == null) ? 4 : Convert.ToInt32(obj); }
            set { ViewState["ZoomLevel"] = value; }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (!Page.ClientScript.IsClientScriptIncludeRegistered("GoogleApi"))
            {
                Page.ClientScript.RegisterClientScriptInclude("GoogleApi", "http://maps.google.com/maps/api/js?sensor=false");
            }


            if (!string.IsNullOrEmpty(CentrePoint))
            {
                if (!Page.ClientScript.IsClientScriptIncludeRegistered("GoogleAjaxApi"))
                {
                    Page.ClientScript.RegisterClientScriptInclude("GoogleAjaxApi", "http://www.google.com/uds/api?file=uds.js&v=1.0&key=" + ApiKey);
                }
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            writer.Write(GetScript());
        }

        private string GetScript()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");


            if (!string.IsNullOrEmpty(CentrePoint))
            {
                sb.AppendLine("var localSearch = new GlocalSearch();");
                sb.Append("localSearch.setSearchCompleteCallback(null, ");
                sb.Append("function() {");
                sb.Append("if (localSearch.results[0]) {");
                sb.Append("var resultLat = localSearch.results[0].lat;");
                sb.Append("var resultLng = localSearch.results[0].lng;");
                sb.Append("var position = new google.maps.LatLng(resultLat,resultLng);");
                sb.Append("LocalSearchCallback(position);");
                sb.Append("}else{");
                sb.Append("alert(\"Location not found\");");
                sb.Append("}");
                sb.AppendLine("});");
                sb.AppendLine("localSearch.execute('" + this.CentrePoint + ", " + this.CentrePointCountry + "');");

                sb.AppendLine("function LocalSearchCallback(position) {");
                sb.AppendLine("var options = {zoom : " + ZoomLevel.ToString() + ",center : position, mapTypeId : google.maps.MapTypeId." + Enum.GetName(typeof(GoogleMapType), this.MapType).ToString().ToUpper() + "};");
                sb.AppendLine("var map = new google.maps.Map(document.getElementById('" + this.ClientID + "'), options);");

                if (ShowMarkerAtCentrePoint)
                {
                    sb.AppendLine("var marker = new google.maps.Marker({position:position,map:map,title:\"" + this.MarkerTitle + "\"});");
                }

                sb.AppendLine("}");
            }
            else
            {
                sb.AppendLine(string.Format("var position = new google.maps.LatLng({0}, {1});", Latitude, Longitude));
                sb.AppendLine("var options = {zoom : " + ZoomLevel.ToString() + ",center : position, mapTypeId : google.maps.MapTypeId." + Enum.GetName(typeof(GoogleMapType), this.MapType).ToString().ToUpper() + "};");
                sb.AppendLine("var map = new google.maps.Map(document.getElementById('" + this.ClientID + "'), options);");

                if (ShowMarkerAtCentrePoint)
                {
                    sb.AppendLine("var marker = new google.maps.Marker({position:position,map:map,title:\"" + this.MarkerTitle + "\"});");
                }

            }

            sb.AppendLine("</script>");
            return sb.ToString();
        }

    }

    public enum GoogleMapType
    {
        Roadmap, Satellite, Hybrid, Terrain
    }

}